#include "file.h"
#include <cjson/cJSON.h>
#include <mosquitto.h>
#include <stdlib.h>
#include <unistd.h>  //sleep
#include <stdio.h>
#include <string.h> //strlen

const char* topic_pub = "1718787027582/Device2AIOTSIM";

float read_tem()
{
    float raw, offset, scale, value;
    read_file("/sys/bus/iio/devices/iio:device0/in_temp_raw", &raw);
    read_file("/sys/bus/iio/devices/iio:device0/in_temp_offset", &offset);
    read_file("/sys/bus/iio/devices/iio:device0/in_temp_scale", &scale);

    value = (raw + offset)*scale / 1000;

    return value;
}

float read_hum()
{
    float raw, offset, scale, value;
    read_file("/sys/bus/iio/devices/iio:device0/in_humidityrelative_raw", &raw);
    read_file("/sys/bus/iio/devices/iio:device0/in_humidityrelative_offset", &offset);
    read_file("/sys/bus/iio/devices/iio:device0/in_humidityrelative_scale", &scale);

    value = (raw + offset)*scale / 1000;

    return value;
}

//消息处理函数
void on_message(struct mosquitto * client, void * obj, const struct mosquitto_message * msg)
{
    //打印消息主题
    printf("Topic: %s\n", msg->topic);
    printf("%*s\n", msg->payloadlen, msg->payload);
}

int main()
{
    //初始化函数库
    mosquitto_lib_init();

    //创建客户端
    struct mosquitto* client = mosquitto_new("mqttx_38858fe3", true, NULL);
    if (!client)
    {
        perror("mosquitto_new");
        mosquitto_lib_cleanup();
        return EXIT_FAILURE;
    }

    //注册消息处理函数
    mosquitto_message_callback_set(client, on_message);

    //连接服务器
    int error = mosquitto_connect(client, "mqtt.yyzlab.com.cn", 1883, 60);
    if (error != MOSQ_ERR_SUCCESS)
    {
        printf("mosquitto_connect: %s\n", mosquitto_strerror(error));
        mosquitto_destroy(client);
        mosquitto_lib_cleanup();
        return EXIT_FAILURE;
    }

    printf("connected to MQTT broker\n");

    //订阅主题
    error = mosquitto_subscribe(client, NULL, "testtopic/#", 0);
    if (error != MOSQ_ERR_SUCCESS)
    {
        printf("mosquitto_subscribe: %s\n", mosquitto_strerror(error));
    }

    //启动心跳线程
    mosquitto_loop_start(client);

    while(1)
    {
        cJSON* obj = cJSON_CreateObject();
        cJSON_AddNumberToObject(obj, "tem", read_tem());
        cJSON_AddNumberToObject(obj, "hum", read_hum());
        cJSON_AddNumberToObject(obj, "id", 0);
        //cJSON_AddBoolToObject(obj, "infrared", cJSON_False);
        char* msg = cJSON_Print(obj);
        //发布消息
        error = mosquitto_publish(client, NULL, topic_pub, strlen(msg), msg, 0, false);
        if (error != MOSQ_ERR_SUCCESS)
        {
            printf("mosquitto_publish: %s\n", mosquitto_strerror(error));
        }
        sleep(5);
    }

    mosquitto_loop_stop(client, false);

    //销毁客户端
    mosquitto_destroy(client);

    //清理函数库
    mosquitto_lib_cleanup();

    return EXIT_SUCCESS;
}